<?php
declare (strict_types = 1);

namespace app\controller;

use app\common\BaseController;
use app\service\TaskService;
use app\service\UserService;
use think\facade\Validate;
use think\file\UploadedFile;
use think\Request;

class TaskController extends BaseController
{
    /**
     * 任务列表
     *
     * @return \think\Response
     */
    public function index(Request $request)
    {
      $page = $request->param('page', 1);
      $pageSize = $request->param('pageSize', 10);
      $taskUserId = $request->param('task_user_id', '');
      $checkUserId = $request->param('check_user', '');
      $project = $request->param('project_id', '');
//      $devStatus = $request->param('dev_status', '');
      $taskStatus = $request->param('task_status', '');
      $isCheck = $request->param('is_check', '');
      $departmentId = $request->param('departmentId', []);
      $conditions = [
        ['t.status', 0, '<>']
      ];
      // 若为检察员（可看自己的任务与所有需检查任务）
      $orConditions = [];
      if ($isCheck && $checkUserId) {
        $conditions[] = ['t.is_check', 1, '='];
        $orConditions = [
          ['t.is_check', '=', 1],
          ['t.status', '<>', 0]
        ];
        if ($taskUserId) {
          $orConditions[] = ['t.task_user_id', '=', $taskUserId];
        }
        if ($project) {
          $orConditions[] = ['t.project_id', '=', $project];
        }
//        if ($devStatus) {
//          $orConditions[] = ['t.dev_status', '=', $devStatus];
//        }
        if ($taskStatus) {
          switch ($taskStatus) {
            // 未开始
            case '1':
              $orConditions[] = ['t.dev_status', '=', 1];
              break;
            // 开发中
            case '2':
              $orConditions[] = ['t.dev_status', '=', 2];
              break;
            // 检查中
            case '3':
              $orConditions[] = ['t.dev_status', '=', 4];
              $orConditions[] = ['t.check_status', '=', 1];
              break;
            // 暂缓
            case '4':
              $orConditions[] = ['t.dev_status', '=', 3];
              break;
            // 已完成
            case '5':
              $orConditions[] = ['t.status', '=', 2];
              break;
          }
        }
        if ($departmentId) {
          $orConditions[] = ['p.department_id', 'IN', $departmentId];
        }
      } else if ($isCheck !== '') {
        $conditions[] = ['t.is_check', $isCheck, '='];
      }
      if ($checkUserId) {
        if ($taskUserId && $taskUserId !== $checkUserId) {
          $conditions[] = ['t.task_user_id', 0, '='];
        } else {
          $conditions[] = ['t.task_user_id', $checkUserId, '='];
        }
      } else if ($taskUserId) {
        $conditions[] = ['t.task_user_id', $taskUserId, '='];
      }
      if ($project) {
        $conditions[] = ['t.project_id', $project, '='];
      }
//      if ($devStatus) {
//        $conditions[] = ['t.dev_status', $devStatus, '='];
//      }
      if ($taskStatus) {
        switch ($taskStatus) {
          // 未开始
          case '1':
            $conditions[] = ['t.dev_status', 1, '='];
            break;
          // 开发中
          case '2':
            $conditions[] = ['t.dev_status', 2, '='];
            break;
          // 检查中
          case '3':
            $conditions[] = ['t.dev_status', 4, '='];
            $conditions[] = ['t.check_status', 1, '='];
            break;
          // 暂缓
          case '4':
            $conditions[] = ['t.dev_status', 3, '='];
            break;
          // 已完成
          case '5':
            $conditions[] = ['t.status', 2, '='];
            break;
        }
      }
      if ($departmentId) {
        $conditions[] = ['p.department_id', $departmentId, 'IN'];
      }
      $order = ['t.status' => 'asc', 'new_status' => 'asc', 't.weight' => 'asc', 't.complete_date' => 'desc', 't.id' => 'desc'];
      $list = TaskService::getInstance()->getTaskJoinProject($conditions, $order, $orConditions);
      foreach ($list as $key => &$value) {
        if (!isset($list[$key + 1]) || ($value['new_status'] === 1 && $list[$key + 1]['new_status'] !== 1)) {
          $value['last'] = true;
          break;
        }
      }
      // 分页
      $count = count($list); //总条数
      $start=intval(($page - 1) * $pageSize); //偏移量，当前页-1乘以每页显示条数
      $pager = [
        'totalCount' => $count,
        'pageSize' => intval($pageSize),
        'currPage' => intval($page),
        'totalPage' => intval($count/$pageSize)+1
      ];
      $data = array_slice($list, $start, intval($pageSize));
      return $this->send200ResponseWithPager($data,$pager);
    }

    /**
     * 新增任务
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
      $data['project_id'] = $request->param('project_id', '');
      $data['task_name'] = $request->param('task_name', '');
      $data['assign_user_id'] = $request->param('assign_user_id', '');
      $data['task_user_id'] = $request->param('task_user_id', '');
      $data['estimated_date'] = $request->param('estimated_date', '');
      $data['file_url'] = $request->param('file_url', []);
      $data['is_check'] = $request->param('is_check', '');
      $data['desc'] = $request->param('desc', '');
      $validate = Validate::rule([
        'project_id' => 'require',
        'task_name' => 'require',
        'assign_user_id' => 'require',
        'task_user_id' => 'require',
        'is_check' => 'require',
        'estimated_date' => 'require',
      ])->message([
        'project_id.require' => '项目不能为空',
        'task_name.require' => '任务名不能为空',
        'is_check.require' => '是否检查不能为空',
        'assign_user_id.require' => '发布者不能为空',
        'task_user_id.require' => '开发人员不能为空',
        'estimated_date.require' => '预计完成日期不能为空'
      ]);
      if (!$validate->check($data)) {
        return $this->send400Response($validate->getError());
      }
      $result = TaskService::getInstance()->createTask($data);
      if ($result['status']) {
        return $this->send200Response('ok');
      } else {
        return $this->send400Response($result['msg']);
      }
    }

    /**
     * 获取指定任务详情
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
      $conditions = [
        ['t.status', 0, '<>'],
        ['t.id', $id, '=']
      ];
      $list = TaskService::getInstance()->getTaskJoinProject($conditions, ['t.id' => 'desc']);
      // 获取文件信息
      $fileList = TaskService::getInstance()->getTaskFileByCondition([['task_id', $id, '=']]);
      // 获取日志信息
      $noteList = TaskService::getInstance()->getTaskFileJoinUser([['n.task_id', $id, '='], ['n.status', 1, '=']]);
      foreach ($noteList as &$value) {
        // 获取日志文件
        $path = TaskService::getInstance()->getNotePathByCondition([['task_note_id', $value['id'], '='], ['status', 1, '=']]);
        if ($path) {
          $value['images'] = $path;
        }
      }
      $data = [];
      if ($list) {
        $data = $list[0];
        $data['fileList'] = [];
        $data['logList'] = [];
        foreach ($fileList as $fv) {
          $data['fileList'][] = [
            'name' => $fv['file_name'],
            'url' => 'https://if.prowealthgroup.cn/task-produce'.$fv['file_url'],
            'downUrl' => 'D:/project/new/task-admin/'.$fv['file_url'],
          ];
        }
        foreach ($noteList as $nv) {
          $add = $nv;
          $add['images'] = [];
          $add['paths'] = [];
          if (isset($nv['images']) && $nv['images']) {
            foreach ($nv['images'] as $iv) {
              $add['images'][] = [
                'name' => $iv['file_name'],
                'url' => 'https://if.prowealthgroup.cn/task-produce'.$iv['file_url'],
                'downUrl' => 'D:/project/new/task-admin/'.$iv['file_url']
              ];
              $add['paths'][] = 'https://if.prowealthgroup.cn/task-produce'.$iv['file_url'];
            }
          }
          $data['logList'][] = $add;
        }
      }
      return $this->send200Response($data);
    }

    /**
     * 编辑指定任务
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
      $data = $request->param('data', []);
      if ($data) {
        $result = TaskService::getInstance()->updateTask($id, $data);
        if (!$result['status']) {
          return $this->send400Response($result['msg']);
        }
      }
      return $this->send200Response('ok');
    }

    /**
     * 删除指定任务
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
      $result = TaskService::getInstance()->deleteTask($id);
      if ($result['status']) {
        return $this->send200Response('ok');
      }
      return $this->send400Response($result['msg']);
    }

    /**
     * 上传文件
     */
    public function upload(Request $request) {
      // 获取表单上传文件 例如上传了001.jpg
      $file = request()->file('file');
      $fileName = $file->getOriginalName();
      // 扩展名
      $ext = $file->getOriginalExtension();
      // 文件名改为时间戳+文件名
      $newFileName = md5($fileName.time()).'.'.$ext;
      $fileReturn = [
        'name' => $fileName,
        'url' => '',
        'downUrl' => ''
      ];
      try {
        $path = '/task/'.date('Ymd');
        $allPath = \think\facade\Filesystem::path($path).'/'.$newFileName;
        $explode = explode('task-produce', $allPath);
        $fileReturn['url'] = 'https://if.prowealthgroup.cn/task-produce'.$explode[1];
        // 上传到本地服务器   默认上传到runtime/storage目录下面生成以当前日期为子目录
        $res = \think\facade\Filesystem::putFileAs($path, $file, $newFileName);
        if (!$res) {
          return $this->send400Response('上传失败');
        }
        $fileReturn['downUrl'] = $allPath;
      } catch (\Exception $e) {
        return $this->send400Response($e->getMessage());
      }
      return $this->send200Response($fileReturn, '上传成功');
    }

    /**
     * 下载文件
     */
    public function download(Request $request) {
      $url = $request->param('url', '');
      $filename = $request->param('name', '');
      $ua = $_SERVER["HTTP_USER_AGENT"];
      $encoded_filename = trim(urlencode($filename));
      $contents = file_get_contents($url);
      $file_size = filesize($url);
      header("Content-type: application/octet-stream;charset=utf-8");
      header("Accept-Ranges: bytes");
      header("Access-Control-Expose-Headers: Content-Disposition");
      header("Accept-Length: $file_size");
      header('Cache-Control: max-age=0');
      if (preg_match("/Firefox/", $ua)) {
        header('Content-Disposition: attachment; filename="'.$filename.'"');
      } else if (preg_match("/Chrome/", $ua)) {
        header('Content-Disposition: attachment; filename='.$encoded_filename);
      } else {
        $encoded_filename = str_replace("+", "%20", $encoded_filename);
        header('Content-Disposition: attachment; filename="'.$encoded_filename.'"');
      }
      exit($contents);
    }

    /**
     * 删除文件
     */
    public function downloadCancel(Request $request) {
      $url = $request->param('url', '');
      $status = unlink($url);
      if (!$status) {
        return $this->send400Response('删除失败');
      }
      return $this->send200Response('ok');
    }

    /**
     * 改变权重
     */
    public function weight(Request $request, $id) {
      $weight = $request->param('weight', '');
      $type = $request->param('type', '');
      if (!$weight || !$type) {
        return $this->send400Response('缺少必要参数');
      }
      $result = TaskService::getInstance()->updateWeight($id, $type, $weight);
      if (!$result['status']) {
        return $this->send400Response($result['msg']);
      }
      return $this->send200Response('ok');
    }
}
